<template>
<!-- 项目例会 -->
  <div class="bimface-test-page">
    <div class="bimface-test">
      <div class="btns" style="left: 80px; top: 10px;" v-if="hasShowBtn">
        <el-button v-if="hasTabAdd" type="primary" @click="handleAddLabel">新建标签</el-button>
        <el-button v-if="hasTabSet" type="primary" @click="labelManageFn">标签管理</el-button>
        <el-button v-if="hasTabSet" type="primary" @click="noteManageVisible = true">批注管理</el-button>
      </div>
      <bim-face-pro
        ref="bimfaceMain"
        :loaderOptions="loaderOptions"
        :webAppOptions="webAppOptions"
        :viewAddedFn="handleViewLoad"
        :eventFn="eventFn">
      </bim-face-pro>
    </div>
    <el-dialog
      class="set-label-dialog"
      append-to-body
      title="标签设置"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      :visible="visible"
      :width="$setRem(500)"
      :before-close="handleClose">
      <div class="content">
        <div class="row">
          <span class="label">标签标题</span>
          <div class="input-content">
            <el-input placeholder="请输入内容" v-model="text"></el-input>
          </div>
        </div>
      </div>
      <div class="content">
        <div class="row">
          <span class="label">标签类型</span>
          <div class="input-content">
            <el-select
              placeholder="请选择标签类型"
              v-model="labelType">
              <el-option :value="1" label="质量" title="质量"></el-option>
              <el-option :value="2" label="安全" title="安全"></el-option>
            </el-select>
          </div>
        </div>
      </div>
      <div class="content">
        <div class="row">
          <span class="label">标签批注</span>
          <div class="input-content">
            <el-select
              placeholder="请选择对应批注"
              v-model="noteId">
              <el-option
                v-for="item in noteList"
                :value="item.id"
                :label="item.content"
                :key="item.id"
                :title="item.content"
              >
              </el-option>
            </el-select>
          </div>
        </div>
      </div>
      <div class="content" v-show="imgUrl">
        <el-image
          style="width: 100px; height: 100px"
          :src="imgUrl"
          :preview-src-list="[imgUrl]">
        </el-image>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="visible = false">取 消</el-button>
        <el-button
          class="success"
          type="primary"
          :loading="loading"
          @click="handleSave">
          保 存
        </el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="imgVisible">
      <el-image
        style="width: 100%;"
        :src="dialogImageUrl"
        :preview-src-list="[dialogImageUrl]">
      </el-image>
    </el-dialog>
    <el-dialog
      class="marker-content-dialog"
      :title="markerContent.content
        ? markerContent.content : '详情'"
      :width="$setRem(800)"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      :visible.sync="markerVisible">
      <div class="content">
        <p>批注信息：{{ markerContent.bimfaceNote && markerContent.bimfaceNote.content || ''}}</p>
        <el-image
          v-if="dialogImageUrl"
          style="width: 100%;"
          :src="dialogImageUrl"
          :preview-src-list="[dialogImageUrl]">
        </el-image>
      </div>
    </el-dialog>
    <label-manage
      :visible="labelManageVisible"
      @change="handleLabelChange"
      @cancel="labelManageVisible = false">
    </label-manage>
    <note-manage
      :fileId="fileId"
      :visible="noteManageVisible"
      @cancel="noteManageVisible = false">
    </note-manage>
  </div>
</template>

<script>
import BimFacePro from '@/components/bimface/project';
import labelManage from '@/components/project/comprehensive/labelManage';
import noteManage from '@/components/project/comprehensive/noteManage';
import linePng from '../../../assets/images/line.png';
import qualityImg from '@/assets/images/car/quality.jpg';
import locationImg from '@/assets/images/car/location.png';
import securityImg from '@/assets/images/car/security.jpg';
// import securityWarnImg from '@/assets/images/car/security_warn.jpg';

export default {
  data() {
    return {
      // 图片展示弹框
      imgVisible: false,
      // 是否展示标签按钮
      hasShowBtn: false,
      // 展示弹框图片Url
      dialogImageUrl: '',
      // bimface挂在dom
      bimDom: null,
      // 当前标注ID
      noteId: '',
      // 批注列表
      noteList: [],
      // 标签列表
      labelList: [],
      // 随机角度
      angleList: [],
      fileId: '2111494517541504',
      // bimface主模型配置
      loaderOptions: {
        viewToken: '7fa84e8d49d046e2a933becf43bf0f38'
      },
      webAppOptions: {
        // 取消 轮廓框
        enableBorderLine: false,
        enableLogarithmicDepthBuffer: true
      },
      BimConfig: {},
      mapConfig: null,
      // 模型实例
      viewer: null,
      // 引线标签实例
      drawable: null,
      // 地图对象
      mapApp: null,
      // 当前点击模块的数据
      currentData: null,
      // 批注
      modelViewer: {
        toolbar: undefined, // 工具条
        annotationmanager: undefined, // annotation的绘制管理器
        annotationToolbar: undefined,
        annotationControl: undefined, // 重写annotation的保存、取消
      },
      // 三维标签的配置类
      markerConfig: null,
      // 三维标签的实例
      marker: null,
      // 标签信息弹框
      markerVisible: false,
      markerContent: {},
      visible: false,
      type: 'add',
      // 标签标题
      text: '',
      // 标签类型 1 质量 2 安全
      labelType: 1,
      loading: false,
      labelManageVisible: false,
      noteManageVisible: false
    };
  },
  computed: {
    imgUrl() {
      const item = this.noteList.find(item => item.id === this.noteId);
      return item ? this.$checkUrl(item.images) : '';
    },
    projectName() {
      return this.$store.state.currentProjectInfo.projectName;
    },
    projectId() {
      return this.$store.state.currentProjectId;
    }
  },
  watch: {
    visible(val) {
      if (!val) {
        this.text = '';
        this.loading = false;
        this.noteId = '';
      }
    },
    labelList(list) {
      if (Array.isArray(list) && list.length) {
        list.forEach(item => this.setMarkerItem(item));
      }
    }
  },
  async created() {
    await this.getBimfaceList();
  },
  mounted() {
    this.bimDom = document.getElementById('bimface');
    this.getBimNoteList();
  },
  components: {
    BimFacePro,
    labelManage,
    noteManage
  },
  methods: {
    /**
     * 获取模型列表
     */
    async getBimfaceList() {
      const { success, data: { data }} = await this.$Model.getBimfaceList({
        // project_name: this.projectName,
        projectId: this.projectId,
        pageFlag: false,
        moduleType: '4', // 主页模型
      });
      if (success && data) {
        const list = data.list || [];
        const currentItem = list[0];
        if (currentItem) {
          const { viewToken, fileId } = currentItem;
          await this.getBimConfig(currentItem);
          this.fileId = fileId;
          this.loaderOptions = {
            viewToken: viewToken
          };
          return;
        }
        this.$message.warning('暂无模型');
      }
    },
    // 获取模型配置
    async getBimConfig({ fileId }) {
      const { success, data: { data }} = await this.$Model.getBimConfig({
        pageFlag: false,
        fileId
      });
      if (success && data) {
        const list = data.list || [];
        this.BimConfig = list[0] || {};
      }
    },
    /**
     * 获取对应bimface模型批注
     */
    async getBimNoteList() {
      const { success, data: { data }} = await this.$Model.getBimNoteList({
        pageFlag: false,
        fileId: this.fileId
      });
      if (success && data) {
        this.noteList = data.list || [];
      }
    },
    /**
     * 获取对应bimface模型标签
     */
    async getBimLabel() {
      const { success, data: { data }} = await this.$Model.getBimLabel({
        pageFlag: false,
        fileId: this.fileId
      });
      if (success && data) {
        this.labelList = data.list || [];
      }
    },
    /**
     * bimface图层加载完成
     */
    handleViewLoad(viewer, viewApp) {
      /* eslint-disable */
      this.viewer = viewer;
      const {
        lng = 0,
        lat = 0,
        pointX = 0,
        pointY = 0,
        height = 0,
        radian = 0
      } = this.BimConfig;
      const mapConfig = new Glodon.Bimface.Plugins.TileMap.MapConfig();
      mapConfig.viewer = viewer;
      // 设置模型载入的基点
      mapConfig.basePoint = {
        x: pointX,
        y: pointY
      };
      // 设置模型载入基点所对应的经纬度（WGS84）
      // mapConfig.modelPosition = [lng, lat];
      mapConfig.modelPosition = [119.75946981717281, 30.381455410645202];
      // 设置模型的旋转弧度值
      mapConfig.modelRotationZ = radian;
      // mapConfig.modelRotationZ = 22 * Math.PI / 180;
      // 设置模型零零标高对应的高程值，单位为米
      mapConfig.modelAltitude = height;
      this.mapConfig = mapConfig;
      // 构造地图对象
      this.mapApp = new Glodon.Bimface.Plugins.TileMap.Map(mapConfig);
      // 设置地图类型为天地图的影像底图
      this.mapApp.setMapSource({
        url: 'http://t0.tianditu.gov.cn/img_w/wmts?tk=ebbfd0ea032ff7f43004fdbe059fe4cf',
        provider: 'Tianditu',
        credit: Glodon.Bimface.Common.Credit.Tianditu
      });
      this.hasShowBtn = true;
      // this.setBimfaceBtn(viewer, viewApp);
      this.setAnnotation(viewer);
      this.setMarker3D();
      // this.setDrawable();
      this.getBimLabel();
      // 渲染场景
      viewer.render();
    },
    // 设置标签
    setDrawable() {
      const drawableConfig = new Glodon.Bimface.Plugins.Drawable.DrawableContainerConfig();
      drawableConfig.viewer = this.viewer;
      drawableConfig.maxNum = 10;
      this.drawable = new Glodon.Bimface.Plugins.Drawable.DrawableContainer(drawableConfig);
    },
    // 初始化三维标签
    setMarker3D() {
      this.markerConfig = new Glodon.Bimface.Plugins.Marker3D.Marker3DContainerConfig();
      this.markerConfig.viewer = this.viewer;
      this.marker = new Glodon.Bimface.Plugins.Marker3D.Marker3DContainer(this.markerConfig);
    },
    /**
     * @param viewer: bimface实例
     * @param viewApp
     */
    setBimfaceBtn(viewer, viewApp) {
      /* eslint-disable */
      // 获取工具条对象
      const toolbar = viewApp.getToolbar('MainToolbar');
      const btnConfig = new Glodon.Bimface.UI.Button.ButtonConfig();
      // 设置新增按钮
      const btn = new Glodon.Bimface.UI.Button.Button({
        ...btnConfig,
        title: '批注'
      });
      btn.setHtml(`<button class="bt-annotation-btn">批注</button>`);
      //设置按钮的位置
      toolbar.addControl(btn);
      //设置按钮的点击事件
      btn.addEventListener('Click', () => this.createAnnotation(viewer, viewApp));
    },
    // 事件绑定
    eventFn(viewer) {
      const evtType = Glodon.Bimface.Application.WebApplication3DEvent.ComponentsSelectionChanged;
      viewer.addEventListener(evtType, this.getEventData);
    },
    // 获取点击数据
    getEventData(data) {
      const { objectId, modelId, objectType } = data;
      if (!objectId || !modelId) {
        this.currentData = null;
        return;
      }
      this.currentData = data;
    },
    // 标签管理
    labelManageFn() {
      this.labelManageVisible = true;
    },
    // 新建标签
    handleAddLabel() {
      if (!this.currentData) {
        this.$message.warning('请选择模型区域');
        return;
      }
      this.type = 'add';
      this.visible = true;
    },
    handleClose() {
      this.visible = false;
    },
    // 设置三维标签
    setMarkerItem(options) {
      if (!options) return;
      const { content, worldPosition, bimfaceNote, labelType,
        objectId, positionX, positionY, positionZ } = options;
      const marker3dConfig = new Glodon.Bimface.Plugins.Marker3D.Marker3DConfig();
      const imgOptions = {
        '1': qualityImg,
        '2': securityImg
      };
      const currentImg = imgOptions[labelType];
      marker3dConfig.size = 40;
      marker3dConfig.src = imgOptions[labelType] || locationImg;
      marker3dConfig.worldPosition = {
        x: Number(positionX),
        y: Number(positionY),
        z: Number(positionZ)
      };
      const marker3d = new Glodon.Bimface.Plugins.Marker3D.Marker3D(marker3dConfig);
      marker3d.onClick(() => {
        const { bimfaceNote } = options;
        this.markerContent = options;
        this.dialogImageUrl = bimfaceNote ? this.$checkUrl(bimfaceNote.images) : '';
        this.markerVisible = true;
      });
      this.marker.addItem(marker3d);
      // this.viewer.clearSelectedComponents();
      this.viewer.render();
    },
    // 清除三维标签
    clearMarker() {
      this.marker.clear();
    },
    /**
     * 添加三维标签
     * @param {?Array} arr
     */
    setMarkers(arr) {
      const list = arr || this.labelList;
      if (Array.isArray(list) && list.length) {
        list.forEach(item => this.setMarkerItem(item));
      }
    },
    // 设置自定义标签
    setCustomItem(options = {}) {
      const { content, worldPosition, bimfaceNote,
        objectId, positionX, positionY, positionZ } = options;
      // 创建自定义元素，可以是一个dom element，也可以是个字符串
      const config = new Glodon.Bimface.Plugins.Drawable.CustomItemConfig();
      const contentDom = document.createElement('div');
      const currentImg = bimfaceNote ? this.$checkUrl(bimfaceNote.images) : this.imgUrl;
      contentDom.innerHTML = `<div class="leadTips">
        <div style="width:49px;height:35px;">
          <img src="${linePng}" height="35" width="49"/>
        </div>
        <div class="leadText canvasDiv"
          style="position: absolute;width:320px;min-height:90px;background:rgba(9,8,50,.9);
          padding:20px;border-radius:10px;top:0;left:45px;">
          ${content ? `<div style="height:30px;line-height:30px;">标签内容：${content}</div>` : ''}
          ${bimfaceNote && bimfaceNote.content
            ? `<div style="height:30px;line-height:30px;display:block;">批注信息：${bimfaceNote.content}</div>`
            : ''
          }
          ${currentImg ? `<img src="${currentImg}" style="width: 100%;height:calc(100% - 60px);"/>` : ''}
        </div>
      </div>`;
      config.viewer = this.viewer;
      config.content = contentDom;
      config.objectId = objectId;
      config.worldPosition = worldPosition
        ? worldPosition
        : {
          x: positionX,
          y: positionY,
          z: positionZ
        };
      // 生成customItem实例
      const customItem = new Glodon.Bimface.Plugins.Drawable.CustomItem(config);
      // 添加自定义标签
      customItem.onClick(() => {
        if (!currentImg) return;
        this.dialogImageUrl = currentImg;
        this.imgVisible = true;
      });
      this.drawable.addItem(customItem);
    },
    // 设置标签
    setLabel(options = {}) {
      if (!this.drawable || !this.viewer) return;
      // 引线标签的配置类
      const config = new Glodon.Bimface.Plugins.Drawable.LeadLabelConfig();
      config.offset = { x: 27, y: -47 };
      config.viewer = this.viewer;
      config.text = this.text;
      config.objectId = options.objectId;
      config.worldPosition = options.worldPosition;
      const label = new Glodon.Bimface.Plugins.Drawable.LeadLabel(config);
      // 引线标签的双击事件
      // label.onDoubleClick((item) => {
      // });
      this.drawable.addItem(label);
    },
    // 重置标签
    handleLabelChange() {
      this.clearMarker();
      this.setMarkers();
    },
    // 保存当前标签
    async handleSave() {
      if (!this.currentData) {
        this.$message.warning('请选择模型构件！');
        return;
      } else if (!this.text) {
        this.$message.warning('内容不能为空！');
        return;
      }
      const {
        objectId,
        worldPosition
      } = this.currentData;
      const newPosition = {};
      worldPosition && Object.keys(worldPosition).forEach(key => {
        newPosition[key] = worldPosition[key] + '';
      });
      const params = {
        objectId,
        noteId: this.noteId,
        positionX: newPosition.x,
        positionY: newPosition.y,
        positionZ: newPosition.z,
        fileId: this.fileId,
        content: this.text,
        labelType: this.labelType
      };
      this.loading = true;
      const { success } = this.type === 'add'
        ? await this.$Model.addBimLabel(params)
        : await this.$Model.editBimLabel({
          ...params,
          id: ''
        });
      this.loading = false;
      if (success) {
        this.getBimNoteList();
        this.handleLabelChange();
        this.$message.success('保存成功');
        this.visible = false;
      }
    },
    // 设置批注配置
    setAnnotation(viewer) {
      if (!viewer) return;
      // 调用viewer3D对象的Method，可以继续扩展功能
      this.modelViewer.toolbar = $(this.bimDom).find('.bf-toolbar-bottom');
      const annotationButton = $('<div class="bf-button" style="font-size: 21px;" title="批注">批注</div>');
      $(this.bimDom).find('.bf-toolbar-bottom').append(annotationButton);
      annotationButton.click(() => {
        // 创建批注
        this.createAnnotation(viewer);
      });
    },
    // 设置批注
    createAnnotation(viewer) {
      if (!viewer) return;
      this.modelViewer.toolbar.hide();
      this.clearMarker();
      if (!this.modelViewer.annotationmanager) {
        const config = new Glodon.Bimface.Plugins.Annotation.AnnotationToolbarConfig();
        config.viewer = viewer;
        const annotationToolbar = new Glodon.Bimface.Plugins.Annotation.AnnotationToolbar(config);
        this.modelViewer.annotationToolbar = annotationToolbar;
        this.modelViewer.annotationmanager = annotationToolbar.getAnnotationManager();
        // 移除默认的annotationToolbar control
        const control = $(this.modelViewer.annotationToolbar.domElement.lastElementChild);
        let html = control[0].innerHTML;
        html = '<div class="bf-toolbar bf-toolbar-control">' +
          '<input class="txtInput" placeholder="请输入批注描述" maxlength="30">' +
          html + '</div>';
        this.modelViewer.annotationControl = $(html);
        this.modelViewer.annotationControl.insertAfter(control);
        control.remove();
        this.modelViewer.annotationControl.find('.bf-save').off('click').on('click', () => {
          this.saveAnnotation();
        });
        this.modelViewer.annotationControl.find('.bf-cancel').off('click').on('click', () => {
          this.canelAnnotation();
        });
      }
      this.modelViewer.annotationToolbar.show();
    },
    // 保存批注
    saveAnnotation() {
      // 检查是否有批注
      if (!this.modelViewer.annotationmanager.getAnnotationList().length) {
        this.$message.warning('批注不能为空');
        return false;
      }
      // 检查是否有说明
      const textInput = $.trim(this.modelViewer.annotationControl.find('input').val());
      if (!textInput) {
        this.$message.warning('批注描述不能为空');
        return false;
      }
      // 批注导出快照
      this.modelViewer.annotationmanager.createSnapshot(async (img) => {
        if (!img) return this.$message.warning('保存失败');
        const images = img.split(',')[1];
        const result = await this.$Model.addBimNoteList({
          fileId: this.fileId,
          content: textInput,
          images
        });
        if (result.success) {
          this.$message.success('保存成功');
          this.getBimNoteList();
          this.endDrawing();
        }
      });
    },
    canelAnnotation() {
      this.endDrawing();
    },
    endDrawing() {
      this.modelViewer.annotationControl.find('input').val('');
      // 卸载批注
      this.modelViewer.annotationmanager.endDrawing && this.modelViewer.annotationmanager.endDrawing();
      $(this.modelViewer.annotationToolbar.domElement).addClass('bf-hide');
      this.modelViewer.toolbar.show();
      this.setMarkers();
    }
  }
};
</script>

<style scoped lang="scss">
  @import '../../../assets/styles/dialog';

  .bimface-test {
    width: 100%;
    height: 100%;
    position: relative;
    .btns {
      position: absolute;
      top: 20px;
      left: 50px;
      background: rgba(0, 0, 0, .1);
      display: flex;
      align-items: center;
      z-index: 8;
    }
  }
  .set-label-dialog {
    .content {
      width: 100%;
      padding: 20px;
      display: flex;
      align-items: center;
      justify-content: center;
      .row {
        width: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;
        .input-content {
          flex: 1;
          .el-select {
            width: 100%;
          }
        }
        .label {
          width: 120px;
          display: flex;
          justify-content: center;
          align-items: center
        }
      }
    }
  }
  .marker-content-dialog {
    .content {
      p {
        line-height: 40px;
        margin-bottom: 20px;
      }
    }
  }
</style>
